package com.demo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.dao_admin.UserDAO;
import com.demo.entity.User;

@RestController
@EnableCaching
@RequestMapping("/cache")
public class SpringCacheDemo {
	
	/**
	 * 1、redisTemplate和SpringCache没有关系！！虽然都属于SpringDataRedis一份子
	 * 2、SpringCache帮你省了通用的取数据的代码：比如  从缓存查找->如果没有从数据库查找->丢到缓存中
	 * 3、keyGenerator是为了保证key的唯一性，只用于返回多条数据的情况！
	 */

	@Autowired
	private UserDAO userDAO;

	@RequestMapping("/list")
	@Cacheable(value = "users", keyGenerator = "myKeyGenerator") //给多条数据的方法才需要配置键生成器策略！！目的是为了保证key唯一！推荐规则：该方法的全路径
	public List<User> findAll(String a, Integer b) {
		return userDAO.findAll();//users::com.demo.SpringCacheDemofindAlljava.lang.String&a&java.lang.Integer&1&
	}

	@GetMapping(value = "/{id}")
	@Cacheable(value = "users", key = "#id")
	public User findByID(@PathVariable("id") Long id) {
		return userDAO.findById(id).get();
	}

	@DeleteMapping(value = "/delete/{id}") //delete/38
	@CacheEvict(value = "users", key = "#id")// 删除多条数据的情况如何删除？
	public void delete(@PathVariable("id") Long id) {
		userDAO.deleteById(id);
	}
	
	@PutMapping(value = "/edit/{id}")
	@CachePut(value = "users", key = "#id")//CachePut注解既可用于update，也可用于insert
	public void update(@PathVariable("id") Long id, User user) {
		userDAO.save(user);
	}
	
	@PostMapping(value = "/save")
	@CachePut(value = "users", key = "#user.id")//insert
	public User save(User user) {
		return userDAO.save(user);
	}

}